package com.example.forum_system.controller;

import com.example.forum_system.common.AppVar;
import com.example.forum_system.common.Result;
import com.example.forum_system.common.ResultCode;
import com.example.forum_system.model.ArticleReply;
import com.example.forum_system.model.User;
import com.example.forum_system.service.IArticleReplyService;
import com.example.forum_system.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @BelongsProject: 0.forum_system
 * @BelongsPackage: com.example.forum_system.controller
 * @Author : 游在海里的鱼
 * @CreateTime : 2023-11-13  20:15
 * @Version : 1.0
 * @Description : TODO
 */
@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {

    @Autowired
    IArticleReplyService replyService;

    @PostMapping("/addReply")
    public Result addReply(HttpServletRequest request,ArticleReply reply){
        //1.检验参数
        if(StringUtil.isEmpty(reply.getContent())
                || reply.getArticleId() == null || reply.getArticleId() < 0){
            log.error("评论传入参数异常");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.获得当前用户对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppVar.SESSION_USER);
        //3.添加用户id
        reply.setPostUserId(user.getId());
        //4.添加评价进数据库
        reply.setPostUserId(user.getId());
        if(replyService.insertReply(reply) != 1){
            log.error("评论加入数据库失败");
            return Result.failed(ResultCode.FAILED_CREATE);
        }
        //5.返回结果给前端
        return Result.success();
    }

    @PostMapping("/getReply")
    public Result getReply(Long articleId){
        //1.检验参数
        if(articleId==null || articleId<0){
            log.warn("获取评论时，传入的文章id无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        return Result.success(replyService.selectAllReply(articleId));
    }


}
